﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;
using System.Text;

namespace Nivdal
{
    public partial class Story : System.Web.UI.Page
    {
        private string StoryId;
        GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Story_PageTitle;
            bool IsApproved = false;
            string UserNewsPaperPriv = "1";
            string NewspaperId;
            OnlineUser ou = (OnlineUser)Session["User"];
            if (Request.QueryString["StoryId"] != null)
            {
                StoryId = Request.QueryString["StoryId"];
                

                IsApproved = GND.ReadNivdalBoolData("@StoryId", "Nivdal_IsStoryApproved", StoryId);
                NewspaperId = GND.ReadNivdalIntData("StoryId", "Nivdal_GetNewspaperByStory", StoryId);
                UserNewsPaperPriv = GND.ReadNivdalIntData("UserId", "NewsPapaerId", "Nivdal_GetNewsPaperPrivsLevel", ou.UserId, NewspaperId);
                    
                if ((!IsApproved) && ((UserNewsPaperPriv == "0" || UserNewsPaperPriv == "1")))
                    Response.Redirect("NewsPaper.aspx");               

                if ((IsApproved) && (HttpContext.Current.User.Identity.IsAuthenticated))
                    GND.ExecNivdalSQL("UserId", "StoryId", "Nivdal_MarkStoryAsRead", ou.UserId, StoryId);

                if (!HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    (StoryFormView.FindControl("RatingPanel") as Panel).Visible = false;
                    (StoryFormView.FindControl("AddTalkbackPanel") as Panel).Visible = false;
                }

                if (IsRated())
                    ((Label)this.StoryFormView.Row.FindControl("CounterLabel")).Text = Resources.Resource.Readers_Rating + ": (" + ShowNumberOfEvaluation() + ")";

                if (GND.ReadNivdalBoolData("StoryId", "Nivdal_GetNewspaperDir", StoryId))
                {
                    NewspaperDirPanel.Direction = ContentDirection.RightToLeft;
                    StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"Styles/NewspaperRTL.css\" />";
                }
                else
                {
                    NewspaperDirPanel.Direction = ContentDirection.LeftToRight;
                    StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"Styles/NewspaperLTR.css\" />";
                }
                //this.MessgeLabel.Text = Session["StoryId"].ToString();
                //OnlineUser ou = (OnlineUser)Session["User"];
                //ShowPopUpMsg(GND.ReadNivdalIntData("UserId", "StoryId", "Nivdal_GetUserStoryEvaluation", ou.UserId, StoryId));
            }
            else
                Response.Redirect("~/Newspaper.aspx");

            if (!IsPostBack)
            {
                if (UserNewsPaperPriv == "2" || UserNewsPaperPriv == "3" )
                {
                    HyperLink EditStory = ((HyperLink)this.StoryFormView.FindControl("EditStoryHyperLink"));
                    EditStory.Visible = true;
                    EditStory.NavigateUrl = "~/EditStory.aspx?StoryId=" + StoryId;
                    
                }

                if ((UserNewsPaperPriv == "3") && (!IsApproved))
                {
                    Button ApproveStoryButton = ((Button)this.StoryFormView.Row.FindControl("ApproveStoryButton"));
                    ApproveStoryButton.Visible = true;                        
                }

            }

            (StoryFormView.FindControl("NoTalkBacksLabel") as Label).Visible = ((StoryFormView.FindControl("TalkBacksRepeater") as Repeater).Items.Count == 0);
    

        }

     

        public Boolean AddStoryEvaluation(string StoryEvaluation)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            string returnValue = GND.ReadNivdalIntData("UserId", "StoryId", "Evaluation", "Nivdal_AddStoryEvaluation", ou.UserId, StoryId, StoryEvaluation);
            long number1 = 0;
            bool canConvert = long.TryParse(returnValue, out number1);
            if (canConvert == true)
                return true;
            else
            {
                ShowPopUpMsg("returnValue is " + returnValue);
                return false;
            }
        }

        public string ShowNumberOfEvaluation()
        {
            return GND.ReadNivdalIntData("StoryId", "Nivdal_GetNumberOfStoryEvaluation", StoryId);

        }

        public double ShowEvaluationAvarage()
        {
            return Math.Round(Convert.ToDouble(GND.ReadNivdalStringData("StoryId", "Nivdal_GetAverageOfStoryEvaluation", StoryId)), 2);

        }

        protected bool IsRated()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            if (HttpContext.Current.User.Identity.IsAuthenticated)
                return GND.ReadNivdalBoolData("UserId", "StoryId", "Nivdal_IsUserRated", ou.UserId, StoryId);
            return false;

        }

         protected int UserStoryRatingValue()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            if (IsRated())
            {
                return Convert.ToUInt16(GND.ReadNivdalIntData("UserId", "StoryId", "Nivdal_UserRatedValue", ou.UserId, StoryId));
            }
            else
                return 0;
        }

        

        protected int UserStoryRating()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            if (IsRated())
            {
                //ShowPopUpMsg(GND.ReadNivdalIntData("UserId", "StoryId", "Nivdal_GetUserStoryEvaluation", ou.UserId, StoryId));
                return Convert.ToUInt16(GND.ReadNivdalIntData("UserId", "StoryId", "Nivdal_GetUserStoryEvaluation", ou.UserId, StoryId));
            }
            else
                return 0;
        }





        protected void StoryRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
        {
            Label StoryId = (Label)StoryFormView.FindControl("StoryIdLabel");
            OnlineUser ou = (OnlineUser)Session["User"];

            if (!IsRated())
            {
                if (AddStoryEvaluation( e.Value))
                {

                    e.CallbackResult = "<br /> " + Resources.Resource.Story_LeftSideRatedStory + " " + ShowNumberOfEvaluation() + " " + Resources.Resource.Story_RightSideRatedStory + " " + ShowEvaluationAvarage();
                }
                else
                    e.CallbackResult = "<br /> " + Resources.Resource.Story_RatedFailed + " " + ou.UserId.ToString() + " " + StoryId + " " + e.Value.ToString();

            }

            else

                e.CallbackResult = Resources.Resource.Story_AlreadyRatedStory;
        }


       
    

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        private void ShowPopUpMsg(string msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("alert('");
            sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
            sb.Append("');");
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
        }

        protected void AddTalkBackButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string title = ((TextBox)this.StoryFormView.Row.FindControl("AddTalkBackTitleTextBox")).Text.Trim();
            string text = ((TextBox)this.StoryFormView.Row.FindControl("TalkBackTextTextBox")).Text.Trim();
           

            // Response.Redirect("Default.aspx");
            string returnValue = GND.ReadNivdalIntData("StoryId", "Author", "Title", "text", "Nivdal_AddNewTalkBack", StoryId, ou.UserId, title, text);
            long number1 = 0;
            bool canConvert = long.TryParse(returnValue, out number1);
            if (canConvert == true)
                Response.Redirect("~/Story.aspx?StoryId=" + StoryId);
            else
                ShowPopUpMsg("returnValue is " + returnValue);

        }




        protected void ApproveStoryButton_click(object sender, EventArgs e)
        {
            //ShowPopUpMsg(StoryId);
            string returnValue = GND.ExecNivdalSQL("StoryId", "Nivdal_ApproveStory", StoryId);
            ShowPopUpMsg(returnValue);
            if (returnValue == "ok")
               Response.Redirect("~/Story.aspx?StoryId=" + StoryId);
            else
             ShowPopUpMsg(returnValue);

        }

        protected bool CanDeleteComments(object UserId)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            if ((UserId.ToString() == ou.UserId) || ou.UserAccessLevel == "5" || ou.UserAccessLevel == "4" || ou.NewsPaperPrivsLevel == "2")
                return true;
            return false;            
        }

        protected void DeleteComment(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                GND.ExecNivdalSQL("TalkBackId", "Nivdal_DeleteTalkBack", e.CommandArgument);
                (StoryFormView.FindControl("TalkBacksRepeater") as Repeater).DataBind();
            }
        }

        protected void DeleteStory(object sender, EventArgs e)
        {
            GND.ExecNivdalSQL("StoryId", "Nivdal_DeleteStory", StoryId);
            (StoryFormView.Row.FindControl("DeleteStoryButton") as Button).Visible = false;
            (StoryFormView.Row.FindControl("StoryDeletedPanel") as Panel).Visible = true;
            
        }

        protected void UndeleteStory(object sender, EventArgs e)
        {
            GND.ExecNivdalSQL("StoryId", "Nivdal_UnDeleteStory", StoryId);
            (StoryFormView.Row.FindControl("DeleteStoryButton") as Button).Visible = true;
            (StoryFormView.Row.FindControl("StoryDeletedPanel") as Panel).Visible = false;
        }

        protected bool IsDeletedVisible(object IsDeleted)
        { 
            OnlineUser ou = (OnlineUser)Session["User"];
            return((bool)(IsDeleted) && ou.NewsPaperPrivsLevel == "3");
        }

        protected string StoryBody(Object SB)
        {
            //string SBSrc = SB.ToString();
            //return GlobalFunctions.EncodeHtmlFromText(SBSrc);
            string Text = "", OriginalText = "";
            GlobalFunctions.GetStoryText(StoryId, ref OriginalText, ref Text);
            return Text;
        }

        protected bool DeleteVisible(object IsDeleted)
        { 
            OnlineUser ou = (OnlineUser)Session["User"];
            return ((!((bool)IsDeleted)) && ou.NewsPaperPrivsLevel == "3");
        }

        
    }
}